package com.junmeng.libadapter.common;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.junmeng.libadapter.base.BaseBindView;
import com.junmeng.libadapter.base.BindViewStore;
import com.junmeng.libadapter.base.IBindViewManager;
import com.junmeng.libadapter.utils.BindViewKeyUtil;

import java.util.List;

/**
 * @param <T> item类
 */
public class CommonBindViewManager<T> implements IBindViewManager<T, RecyclerViewHolder, BaseCommonBindView<T>> {
    protected BindViewStore<Integer, BaseCommonBindView<T>> bindViewStore = new BindViewStore<>();

    protected SparseArray<Integer> viewTypeMapLayoutRes = new SparseArray<>();


    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder((RecyclerView) parent, getItemView(parent, viewTypeMapLayoutRes.get(viewType)));
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        bindViewStore.getBindView(BindViewKeyUtil.getKey(t.getClass())).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull RecyclerViewHolder holder, @NonNull T t) {
        BaseBindView bindView = bindViewStore.getBindView(BindViewKeyUtil.getKey(t.getClass()));
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseCommonBindView bindView) {
        bindViewStore.putBindView(BindViewKeyUtil.getKey(bindView.itemBeanType), bindView);
    }

    public View getItemView(@NonNull ViewGroup parent, @LayoutRes int layoutRes) {
        return LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false);
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int viewType = BindViewKeyUtil.getKey(t.getClass());
        BaseCommonBindView baseCommonBindView = bindViewStore.getBindView(viewType);
        if (baseCommonBindView == null) {
            throw new RuntimeException("Don't forget to register " + t.getClass() + " before using");
        }
        int resId = baseCommonBindView.getItemLayoutResId(t);
        viewTypeMapLayoutRes.put(viewType, resId);
        return viewType;
    }
}
